# -*- coding: utf-8 -*-

from core.resources import CustomerModelResource
from import_export.fields import Field
from import_export.widgets import ForeignKeyWidget
from apps.pms.models import Product, Module, Version
from apps.tms.models import Bug
from apps.sys.models import User
from bs4 import BeautifulSoup
from apps.sys.models import DictData


class BugResources(CustomerModelResource):
    product = Field(attribute="product", widget=ForeignKeyWidget(Product, field="name"))
    module = Field(attribute="module", widget=ForeignKeyWidget(Module, field="name"))
    version = Field(attribute="version", widget=ForeignKeyWidget(Version, field="name"))
    towner = Field(attribute="towner", widget=ForeignKeyWidget(User, field="name"))
    downer = Field(attribute="downer", widget=ForeignKeyWidget(User, field="name"))

    def import_row(self, row, instance, **kwargs):
        row["type"] = DictData.objects.get(
            type="tms_bug_type", label=row.get("type")
        ).value
        row["gravity"] = DictData.objects.get(
            type="sys_gravity_level", label=row.get("gravity")
        ).value
        row["status"] = DictData.objects.get(
            type="tms_bug_status", label=row.get("status")
        ).value
        return super().import_row(row, instance, **kwargs)

    @staticmethod
    def dehydrate_type(instance: Bug):
        return DictData.objects.get(type="tms_bug_type", value=instance.type).label

    @staticmethod
    def dehydrate_gravity(instance: Bug):
        return DictData.objects.get(
            type="sys_gravity_level", value=instance.gravity
        ).label

    @staticmethod
    def dehydrate_status(instance: Bug):
        return DictData.objects.get(type="tms_bug_status", value=instance.status).label

    @staticmethod
    def dehydrate_resolved_type(instance: Bug):
        dict_map = DictData.objects.filter(
            type="tms_bug_resolved_type", value=instance.resolved_type
        ).first()
        return dict_map.label if dict_map else None

    @staticmethod
    def dehydrate_description(instance: Bug):
        return BeautifulSoup(instance.description, "lxml").get_text(
            separator="\n", strip=True
        )

    class Meta:
        model = Bug
        fields = (
            "number",
            "name",
            "product",
            "module",
            "type",
            "version",
            "gravity",
            "towner",
            "downer",
            "description",
            "status",
            "resolved_type",
            "remark",
        )
        import_id_fields = ("number",)
        export_order = fields
